import com.fasterxml.jackson.databind.ObjectMapper;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: 石方旭
 * Date: 2022-10-18
 * Time: 19:42
 */
//这里要与JSON对象中的key要匹配,也可以提供对应的Getter/Setter方法
class Message {
    public String from;
    public String to;
    public String message;

    @Override
    public String toString() {
        return "Message{" +
                "from='" + from + '\'' +
                ", to='" + to + '\'' +
                ", message='" + message + '\'' +
                '}';
    }
}
@WebServlet("/message")
    public class MessageWall extends HttpServlet {
    //    //创建ObjectMapper来对请求进行解析
    //    private ObjectMapper objectMapper = new ObjectMapper();
    //    //创建一个List,将收到的请求放到List中保存下来
    //    private List<Message> messageList = new ArrayList<>();
    //    //服务端这边接收到请求之后,然后对请求进行解析
    //    @Override
    //    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    //        System.out.println("1");
    //        //获取到流对象,读取请求的body中的数据,然后对其进行解析成Message类,返回给一个message对象
    //        Message message = objectMapper.readValue(req.getInputStream(),Message.class);
    //        System.out.println("1");
    //        messageList.add(message);
    //        //返回响应给客户端
    //        //将请求加入到List之后提示一下-->打印日志
    //        System.out.println("message : " + messageList);
    //        resp.setContentType("application/json;charset=utf8");
    //        resp.getWriter().write("{ \"ok\" ; 1 }");
    //    }
    // 由于 ObjectMapper 会在多个方法中使用, 就提出来, 作为成员变量
    private ObjectMapper objectMapper = new ObjectMapper();
    private List<Message> messageList = new ArrayList<>();

    // 负责实现让客户端提交数据给服务器.
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        // 1. 把 body 的 json 数据解析出来.
        Message message = objectMapper.readValue(req.getInputStream(), Message.class);
        // 2. 把这个对象保存起来. 最简单的办法, 就是直接存到内存中.
        messageList.add(message);
        System.out.println("message: " + message);
        // 3. 返回保存成功的响应
        resp.setContentType("application/json;charset=utf8");
        resp.getWriter().write("{ \"ok\": 1 }");
    }
}
